package service

import (
	"perfect-admin/dao"
	"perfect-admin/model"
	"perfect-admin/model/request"
)

func GetMessageList(queryInfo request.QueryInfo, user *request.CustomClaims) (Messages []model.SysMessage, total int, err error) {
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&model.SysMessage{}).Where("user_id = ? and type = ? and is_read = ?", user.UserID, queryInfo.Type, queryInfo.IsRead).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("user_id = ? and type = ? and is_read = ?", user.UserID, queryInfo.Type, queryInfo.IsRead).Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("User").Order("id desc").Find(&Messages).Error
		return
	} else {
		if err = dao.DB.Model(&model.SysMessage{}).Where("user_id = ? and type = ? and message like ? and is_read = ?", user.UserID, queryInfo.Type, "%"+queryInfo.Query+"%", queryInfo.IsRead).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("user_id = ? and type = ? and message like ? and is_read = ?", user.UserID, queryInfo.Type, "%"+queryInfo.Query+"%", queryInfo.IsRead).Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("User").Order("id desc").Find(&Messages).Error
		return
	}
}

func GetMessageCount(user *request.CustomClaims) (msg_total int, notice_total int, task_total int, err error) {
	err = dao.DB.Model(&model.SysMessage{}).Where("user_id = ? and type = ? and is_read = 0", user.UserID, "消息").Count(&msg_total).Error
	err = dao.DB.Model(&model.SysMessage{}).Where("user_id = ? and type = ? and is_read = 0", user.UserID, "通知").Count(&notice_total).Error
	err = dao.DB.Model(&model.SysMessage{}).Where("user_id = ? and type = ? and is_read = 0", user.UserID, "任务").Count(&task_total).Error
	return
}


func UpdateMessageIsRead(id int) error {
	return dao.DB.Model(&model.SysMessage{}).Where(&model.SysMessage{ID:id}).Update(&model.SysMessage{IsRead:1}).Error
}
